package cn.jtfadmin.core.modules.sys.service.impl;

import cn.jtfadmin.base.lang.common.service.BaseService;
import cn.jtfadmin.core.modules.sys.domain.entity.SysIdGenEntity;
import cn.jtfadmin.core.modules.sys.service.SysIdGenActionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.Optional;

@Service
@Validated
public class SysIdGenActionServiceImpl implements SysIdGenActionService {

    @Autowired
    private BaseService<SysIdGenEntity> service;




    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
    public Long autoGenId(String type){
        Optional<SysIdGenEntity> optional = service.findOneByField("type", type);
        SysIdGenEntity sysIdGenEntity;
        if(optional.isPresent()){
            sysIdGenEntity = optional.get();
        }else {
            sysIdGenEntity = new SysIdGenEntity();
            sysIdGenEntity.setType(type);
            sysIdGenEntity.setIdNum(0L);
        }
        Long idNum = sysIdGenEntity.getIdNum();
        long id = idNum +1L;
        sysIdGenEntity.setIdNum(id);
        service.save(sysIdGenEntity);
        return id;
    }

}
